/**
 * 
 */
var myBike = {};
myBike.showSetting = {
		state : 1,// 默认显示正常
};
myBike.markers = {
		exceptionMarker : new Array(),
		normalMarker : new Array(),
};

$(function(){
	init()
});

// 初始化
function init(){
	initMap();
}

var map, geolocation = null;
function initMap(){
	map = new AMap.Map('myMap', {
        resizeEnable: true,
        zoom:11,
        //center: [116.397428, 39.90923],
        center: [108.942531,34.270538],
        scrollWheel:true,
    });
	
	//Google图层
//    var googlLayer = new AMap.TileLayer({  
//        tileUrl:"http://mt{1,2,3,0}.google.cn/vt/lyrs=m@142&hl=zh-CN&gl=cn&x=[x]&y=[y]&z=[z]&s=Galil"//图块取图地址  
//    });
//    googlLayer.setMap(map);
	
	map.on('complete', function() {
        //设置城市
        map.setCity('西安市');
        //initMarker();
        initCurrentPosition();
        //map.setFitView();
    });
	
}

// 初始化当前位置
function initCurrentPosition(){
	map.plugin('AMap.Geolocation', function () {
	    geolocation = new AMap.Geolocation({
	        enableHighAccuracy: true,//是否使用高精度定位，默认:true
	        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
	        maximumAge: 0,           //定位结果缓存0毫秒，默认：0
	        convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
	        showButton: true,        //显示定位按钮，默认：true
	        buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
	        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
	        showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
	        showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
	        panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
	        zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
	    });
	    //map.addControl(geolocation);
	    geolocation.getCurrentPosition();
	    AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
	    AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
	});
}

//解析定位结果
function onComplete(data) {
//	console.log(data);
//    var str=['定位成功'];
//    str.push('经度：' + data.position.getLng());
//    str.push('纬度：' + data.position.getLat());
//    str.push('精度：' + data.accuracy + ' 米');
//    str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
//    console.log(str.join('<br>'));
    map.setCenter([data.position.getLng(), data.position.getLat()]);
    map.setZoom(17);
    var marker = new AMap.Marker({
        position: [data.position.getLng(), data.position.getLat()],
        draggable: false,
        cursor: 'move',
        icon: 'http://ditu.amap.com/assets/img/loc_ok.png'
    });
    marker.setMap(map);
    // 设置点标记的动画效果，此处为弹跳效果
    marker.setAnimation('AMAP_ANIMATION_DROP');
 	// 设置鼠标划过点标记显示的文字提示
    marker.setTitle('我的位置');
	// 设置label标签
    /*marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
        offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
        content: "<span style='font-size:10px;font-color:red;'>我的当前位置o(^▽^)o</span>"
    });*/
    // 初始化点
    var newCenter = map.setFitView();
    searchBike(data.position.getLng(), data.position.getLat());
    
}
//解析定位错误信息
function onError(data) {
	console.log(str.join('定位失败'));
}

function initMarker(){
	var showSetting = myBike.showSetting.state;
	if(showSetting == 1){
		clearMap(myBike.markers.exceptionMarker);
		loadMarker('getNormalSite.do', 'http://www.xazxc.com/images/map/zxc_g1.png','normal');
	}
	if(showSetting == 2){
		clearMap(myBike.markers.normalMarker);
		loadMarker('getAbnormalSite.do', 'http://www.xazxc.com/images/map/zxc_r1.png','exception');
	}
	if(showSetting == 3){
		closeMapAll();
		loadMarker('getNormalSite.do', 'http://www.xazxc.com/images/map/zxc_g1.png','normal');
		loadMarker('getAbnormalSite.do', 'http://www.xazxc.com/images/map/zxc_r1.png','exception');
	}
}

var infoWindow = new AMap.InfoWindow({
	offset: new AMap.Pixel(0, -30),
	closeWhenClickMap:true,
});


function loadMarker(url, markerIcon, isNormal){
    $.ajax({
		 type:'post',
		 url:url,
		 dataType:'json',
		 success:function(data){
			siteData = data;
			
			for(var i = 0; i < siteData.length; i++){
				 var siteInfo = siteData[i];
				 siteInfo.isNormal = isNormal;
				 siteInfo.id = i;
				 addMarker(siteInfo);
			}
			map.setFitView();			
			alert(151916161);
		 }
    });  
}

function addMarker(siteData){
		 var siteInfo = siteData;
		 var title = ''+siteInfo.sitename,
		 content = [];
		 content.push("<div style='font-size:10px;'>");
		 content.push("网点编号："+siteInfo.siteid);
		 content.push("网点名称："+siteInfo.sitename);
		 content.push("网点地址："+siteInfo.location);
		 content.push("可租车辆数："+(siteInfo.locknum-siteInfo.emptynum));
		 content.push("可还空位数："+siteInfo.emptynum);
		 content.push("</div>");
		 var lnglat = new AMap.LngLat(siteInfo.longitude, siteInfo.latitude);
		 var id = "marker_normal_bike_"+siteInfo.id;
		 var siteState = 1;
		 var icon = 'http://www.xazxc.com/images/map/zxc_g1.png';
		 if('normal' == siteInfo.isNormal){
			 id = "marker_normal_bike_"+siteInfo.id;
		 }else if('exception' == siteInfo.isNormal){
			 id = "marker_exception_bike_"+siteInfo.id;
			 icon = 'http://www.xazxc.com/images/map/zxc_r1.png';
			 siteState = 2;
		 }else{
			 id = "marker_all_bike_"+siteInfo.id;
			 icon = 'http://www.xazxc.com/images/map/zxc_r1.png';
			 siteState = 2;
		 }
		 
		var marker = new AMap.Marker({
			 id:id,
			 siteState:siteState,
			 icon: icon,
			 position: lnglat,
			 map: map
		});
		marker.content = content.join("<br/>");
		closeInfoWindow();
		//鼠标点击marker弹出自定义的信息窗体
       AMap.event.addListener(marker, 'click', function(e) {
	       	infoWindow.setContent(e.target.content);
	       	map.setCenter(e.target.getPosition());
	       	map.setZoom(17);
	       	map.setFitView(e.target.getPosition());
			infoWindow.open(map, e.target.getPosition());
       });//注册监听，当选中某条记录时会触发
       var showSetting = myBike.showSetting.state;
       if(showSetting == 1){
	       	myBike.markers.normalMarker.push(marker);
	   	}else if(showSetting == 2){
	   		myBike.markers.exceptionMarker.push(marker);
	   	}
}




//关闭信息窗体
function closeInfoWindow() {
    map.clearInfoWindow();
}


//删除地图上制定覆盖物
function clearMap(overlayers) {
	map.remove(overlayers)
}
//删除地图上所有的覆盖物
function clearMapAll() {
    map.clearMap();
}
